﻿import axios from "axios"
import { router } from "../router/index"
import Vue from "vue"
import { Message, Loading } from "element-ui"

import { message } from "@/libs/message.js"

import config from "./config.js"
import JSONBIG from "json-bigint"

import glo_loading from '@/components/loading/index' // loading组件的简单封装
import { apiLoading } from '@/components/loading/loadingConfig'
import store from "@/store"; // 全局的页面跳转loading是否启用

export const ExternalUrl = config.ConfigExternalUrl
export const wsUrl = config.ConfigWsUrl

//使用create方法创建axios实例
export const version = "v1"
export const baseURL = config.ConfigBaseURL
export const ServiceName = "wfpms-master-service"
export const Service = axios.create({
	timeout: 25000, // 请求超时时间
	baseURL: config.ConfigBaseURL, //根路径
	withCredentials: false,
	transformResponse:[data=>{
		//data是原始字符串数据
		const json = JSONBIG({
			storeAsString: true
		})
		return json.parse(data)
	}],
})
/**
 *
 *取消请求发送功能
 */
let pending = []
let cancelToken = axios.CancelToken
let cancelPending = config => {
	pending.forEach((item, index) => {
		if (!!config) {
			if (item.u == config.url) {
				item.f() //取消请求
				pending.splice(index, 1) //移除当前请求记录
			}
		} else {
			item.f() //取消请求
			pending.splice(index, 1) //移除当前请求记录
		}
	})
}
// 获取url中的token
let getQueryString = name => {
	var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i")
	var r = window.location.href.substr(1).match(reg)
	if (r != null) {
		return unescape(r[2])
	}
	return null
}
let getUrlParam = function (name) {
	return (
		decodeURIComponent(
			(new RegExp("[?|&]" + name + "=" + "([^&;]+?)(&|#|;|$)").exec(window.location.href) || [, ""])[1].replace(/\+/g, "%20")
		) || null
	)
}
// 添加请求拦截器
Service.interceptors.request.use(
	config => {

		store.state.show ? glo_loading.loadingShow() : ''
		// 设置请求头token
		var TOKEN = getUrlParam("fullToken") ? getUrlParam("fullToken") : window.sessionStorage.getItem("token")
		var URLTOKEN = getQueryString("token")
		TOKEN = TOKEN ? TOKEN : URLTOKEN ? URLTOKEN : ""
		TOKEN = getUrlParam("fullToken") ? getUrlParam("fullToken") : TOKEN
		window.sessionStorage.setItem("token", TOKEN)
		// console.log(TOKEN, 'TOKEN');
		if (TOKEN) {
			config.headers["token"] = TOKEN
			// cancelPending(config);
			// config.cancelToken = new cancelToken((c) => {
			//   pending.push({'u': config.url, 'f': c});
			// });
		} else {
			router.push("/login")
		}
		return config
	},
	error => {
		store.state.show ? glo_loading.loadingHide() : ''
		store.commit("changeStatus",false)
		Promise.reject(error)
	}
)

Service.interceptors.response.use(
	response => {
		let token = response.headers.token
		if (token) {
			window.sessionStorage.setItem("token", token)
		}
		// else{
		// cancelPending(response.config);
		// }
		const { code, msg } = response.data
		window.sessionStorage.setItem("code", code)

		// console.log("预览PDF",response)

		if (code != "0000") {
			if (code == "0002" || code == "0100" || code == "0001" || code == "0004") {
				response.data.code = "0000"
				// message.error(msg)
				setTimeout(() => {
					router.replace({
						path: "/login",
					})
				}, 2000)
				message.error(msg)
				store.state.show ? glo_loading.loadingHide() : ''
				store.commit("changeStatus",false)
				return Promise.reject(response)
			} else if (!code) {
				//下载接口兼容
				store.state.show ? glo_loading.loadingHide() : ''
				store.commit("changeStatus",false)
				return Promise.resolve(response)
			} else {
				if (code == "0408") {
					store.state.show ? glo_loading.loadingHide() : ''
					store.commit("changeStatus",false)
					return Promise.resolve(response)
				}
				if (code == "0501") {
					store.state.show ? glo_loading.loadingHide() : ''
					store.commit("changeStatus",false)
					return Promise.resolve(response)
				}
				if (code == "9999") {
					store.state.show ? glo_loading.loadingHide() : ''
					store.commit("changeStatus",false)
					return Promise.resolve(response)
				} else {
					message.error(msg)
					store.state.show ? glo_loading.loadingHide() : ''
					store.commit("changeStatus",false)
					return Promise.reject(response)
				}
			}
		} else {
			store.state.show ? glo_loading.loadingHide() : ''
			store.commit("changeStatus",false)
			return Promise.resolve(response)
		}
	},
	error => {
		store.state.show ? glo_loading.loadingHide() : ''
		store.commit("changeStatus",false)
		return Promise.reject(error)
	}
)
